package com.star.project.cococo.util;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.util.Auth;
import com.star.common.utils.Arith;
import com.star.framework.config.RuoYiConfig;
import com.star.framework.web.controller.BaseController;
import com.star.framework.web.domain.AjaxResult;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;

import java.security.SecureRandom;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
public class CommonUtils extends BaseController {

    @Value("${sms.ipyy.url}")
    private String ipyyUrl;
    @Value("${sms.ipyy.account}")
    private String ipyyAccount;
    @Value("${sms.ipyy.password}")
    private String ipyyPassword;
    @Value("${sms.ipyy.smsSign}")
    private String ipyySmsSign;

    @Value("${oss.qiniu.accessKey}")
    private String accessKey;
    @Value("${oss.qiniu.secretKey}")
    private String secretKey;
    @Value("${oss.qiniu.bucket}")
    private String bucket;

    @Value("${token.expire}")
    private Long expire;

    @Autowired
    private RedisUtils redisUtils;

    public static final DecimalFormat df = new DecimalFormat("0.00");
    private static final String SYMBOLS = "0123456789"; // 数字
    private static final Random RANDOM = new SecureRandom();
    private static CloseableHttpClient httpclient;


    /**
     * 保存登录token
     */
    public String saveToken(String loginName,Long userId) {
        String token = loginName + new Date().getTime() ;
        try {
            token = AesEncryptUtils.encrypt(token);
            String key = RuoYiConfig.getName() + userId.toString();
            if(redisUtils.hasKey(key)){
                redisUtils.del(redisUtils.get(key));
            }
            redisUtils.set(key,token);
            redisUtils.set(token, userId.toString(), expire,TimeUnit.DAYS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 获取七牛upToken
     */
    public String getUpToken(){
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        System.out.println("upToken = "+ upToken);
        return upToken;
    }

    /**
     * 获取各种编号
     */
    public String makeCode(String prefix){   //prefix(2) + YYYYMMddHH(8) + 计数器(6)
        SimpleDateFormat dateFormat=new SimpleDateFormat("YYYYMMddHH");
        String key = prefix + dateFormat.format(new Date());
        if(!redisUtils.hasKey(key)){
            redisUtils.set(key,"0",1, TimeUnit.DAYS);
        }
        StringBuffer code = new StringBuffer();
        code.append(prefix);//前缀
        code.append(dateFormat.format(new Date()));
        code.append(String.format("%06d", redisUtils.incr(key,1)));  //计数器
        return code.toString();
    }

    /**
     * 发送短信验证码（ipyy平台）
     */
    public AjaxResult sendSmsIpyy(String mobile) throws Exception {
        //多个手机号用逗号分隔
        //用户ID。
        String userid="";
        String msg = getNonce_str();
        String text = "【"+ ipyySmsSign +"】"+ msg +"为您的验证码，请与15分钟内填写。如非本人操作，请忽略本短信";
        String sendTime="";
        //扩展号，没有请留空
        String extno="";
        List list = new ArrayList();

        list.add(new BasicNameValuePair("action","send"));
        list.add(new BasicNameValuePair("userid", userid));
        list.add(new BasicNameValuePair("account", ipyyAccount));
        list.add(new BasicNameValuePair("password", MD5.GetMD5Code(ipyyPassword)));
        list.add(new BasicNameValuePair("mobile", mobile));
        list.add(new BasicNameValuePair("content", text));
        list.add(new BasicNameValuePair("sendTime", sendTime));
        list.add(new BasicNameValuePair("extno", extno));
        httpclient = SSLClient.createSSLClientDefault();
        HttpPost post = new HttpPost(ipyyUrl);
        post.setEntity(new UrlEncodedFormEntity(list,"utf-8"));
        HttpResponse response = httpclient.execute(post);
        HttpEntity entity = response.getEntity();
        String returnString= EntityUtils.toString(entity);
        System.out.println(returnString);
        JSONObject jsonObject = JSONObject.parseObject(returnString);
        EntityUtils.consume(entity);
        if("Success".equals(jsonObject.get("returnstatus"))){
            redisUtils.set(mobile, msg, 15, TimeUnit.MINUTES);
            return success(mobile + ">>>已发送",jsonObject.get("message"));
        }else{
            return error("发送失败");
        }
    }

    /**
     * 获取长度为 4 的随机数字
     */
    public static String getNonce_str() {
        // 如果需要4位，那 new char[4] 即可，其他位数同理可得
        char[] nonceChars = new char[4];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }
    public Double getNowPrice(String price, long cutCount) {
        Double nowPrice = Arith.round(Arith.sub(Double.valueOf(price), Arith.mul(cutCount,0.1)),1);
        return nowPrice < 0.1 ? 0.1 : nowPrice;
    }

}
